package com.seventh7.mybatis.ref.license;

import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;

import javax.crypto.Cipher;
import javax.xml.bind.DatatypeConverter;

public final class ActivationDriver {

    public static ActivationResult activate(String p0) {
        if (p0 == null || p0.isEmpty()) {
            return ActivationResult.fail("License key invalid");
        } else {
            String[] cracked = doCrack("cracked");
            return ActivationResult.success(new LicenseData(cracked[0], cracked[1]));
        }
    }

    private static String[] doCrack(String name) {
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
            keyPairGen.initialize(512);
            KeyPair keyPair = keyPairGen.generateKeyPair();

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());

            String result = DatatypeConverter.printHexBinary(cipher.doFinal(name.getBytes()));
            String key = DatatypeConverter.printHexBinary(keyPair.getPublic().getEncoded());
            return new String[]{key, result};
        } catch (GeneralSecurityException e) {
            return new String[]{"", ""};
        }
    }

}